# coding:utf-8

import os
from datetime import datetime

import xlwt
from flask import (
    request, current_app, render_template, flash, redirect, url_for, jsonify,
    abort, send_file)
from flask_login import current_user, login_required
from app.models import get_timestamp
from app.wechat.constant import WxUserApprovalStatus
from common.wechat_util import get_user_tags, sync_wechat_menu, get_wxuser_info
from app.extensions import db
from app.op.models import WxUser, User, CancelAttentionUser
from app.api.ip_utils import ip_util
from . import opc_wechat_bp
from .models import WechatTemplate, WechatSendLog, WechatTag, WechatMenu
from .forms import WechatTemplateForm, SearchWechatLogForm, WechatMenuForm, SearchWechatListForm
from .utils import generate_menu_pid_choice


@opc_wechat_bp.route('/wechat_user_list', methods=['GET', 'POST'])
def wechat_user_list():
    """
    created by chenhj at 2017/7/25

    """
    form = SearchWechatListForm(formdata=request.form or request.args)

    url_kwargs = {}
    user_query = WxUser.query
    if form.validate():

        query_kwargs, url_kwargs = form.generate_kwargs()

        # 根据 form 表单的值，构造Demand的query对象
        user_query = WxUser.generate_list_query_condition(
            args=query_kwargs,
            query=user_query
        )

    if form.is_invite_user.data == 2:
        user_query = user_query.filter(
            WxUser.invite_user_id != 0
        )
    elif form.is_invite_user.data == 1:
        user_query = user_query.filter(
            WxUser.invite_user_id == 0
        )

    page = request.args.get('page', 1, type=int)
    pagination = user_query.order_by(
        WxUser.subscribe_time.desc()
    ).paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False
    )
    wechat_users = pagination.items
    return render_template(
        'wechat_user_list.html',
        wechat_users=wechat_users,
        pagination=pagination,
        page=page,
        form=form,
        url_kwargs=url_kwargs
    )


@login_required
@opc_wechat_bp.route('/ground_user_list', methods=['GET', 'POST'])
def ground_user_list():
    """
    create by ld_wu 2018-02-27
    地推邀请用户列表
    """
    form = SearchWechatListForm(True, formdata=request.form or request.args)

    url_kwargs = {}
    user_query = WxUser.query.filter(
        WxUser.is_ground.__eq__(True)
    )
    if form.validate():

        query_kwargs, url_kwargs = form.generate_kwargs()

        user_query = WxUser.generate_list_query_condition(
            args=query_kwargs,
            query=user_query
        )

    if form.is_invite_user.data == 2:
        user_query = user_query.filter(
            WxUser.invite_user_id != 0
        )
    elif form.is_invite_user.data == 1:
        user_query = user_query.filter(
            WxUser.invite_user_id == 0
        )

    page = request.args.get('page', 1, type=int)
    pagination = user_query.order_by(
        WxUser.subscribe_time.desc()
    ).paginate(
        page,
        error_out=False
    )
    wechat_users = []
    items = pagination.items
    for each in items:
        each.ip_city = ''
        if each.ip_address:
            ip_info = ip_util.find(each.ip_address)
            try:
                each.ip_city = '{}{}'.format(ip_info[1], ip_info[3])
            except:
                pass

        wechat_users.append(each)
    return render_template(
        'ground_user_list.html',
        wechat_users=wechat_users,
        pagination=pagination,
        page=page,
        form=form,
        url_kwargs=url_kwargs
    )


@opc_wechat_bp.route('/export/ground_users')
@login_required
def export_ground_users():
    """
    create by ld_wu 2018-03-06
    导出地推用户
    """
    form = SearchWechatListForm(True, formdata=request.form or request.args)

    user_query = WxUser.query.filter(
        WxUser.is_ground.__eq__(True)
    )
    if form.validate():

        query_kwargs, url_kwargs = form.generate_kwargs()

        user_query = WxUser.generate_list_query_condition(
            args=query_kwargs,
            query=user_query
        )

    if form.is_invite_user.data == 2:
        user_query = user_query.filter(
            WxUser.invite_user_id != 0
        )
    elif form.is_invite_user.data == 1:
        user_query = user_query.filter(
            WxUser.invite_user_id == 0
        )

    template_path = '/tmp/ground_users_{}.xls'.format(datetime.now())
    book = xlwt.Workbook(encoding='utf-8')
    fields = ['昵称', '电话号码', '关注时间', '关注状态', '地推人员',
              '邀请时间', 'GPS定位', '绑定时间', '审核状态']

    sheet = book.add_sheet('地推用户信息')

    for index, value in enumerate(fields):
        sheet.write(0, index, value)

    for index, ground_user in enumerate(user_query.all()):
        user = ground_user.user
        mobile = '-'
        if user:
            mobile = user.mobile
        else:
            if ground_user.certify_time:
                cancel_user = CancelAttentionUser.get_by_args(
                    wx_openid=ground_user.openid
                )
                if cancel_user:
                    mobile = cancel_user.mobile
        values = [
            ground_user.nickname,
            mobile,
            str(ground_user.subscribe_time_display),
            ground_user.subscribe_display,
            ground_user.invite_user.nickname,
            str(ground_user.invite_time_display or ''),
            ground_user.coordinates_display,
            str(ground_user.certify_time_display),
            ground_user.approval_status_display
        ]
        for num, value in enumerate(values):
            sheet.write(index+1, num, value)
    book.save(template_path)
    if not os.path.exists(template_path):
        abort(404)
    return send_file(template_path, as_attachment=True)


@login_required
@opc_wechat_bp.route('/ground_user/approval', methods=['POST'])
def approval_ground_user():
    """
    create by ld_wu 2018-02-27
    地推用户审核
    :return:
    """
    data = request.get_json()
    user_id = data['user_id']
    status = data['status']
    user = WxUser.get_by_id(user_id)
    if user.approval_status == WxUserApprovalStatus.DEFAULT.value:
        user.approval_status = status
        user.approval_user_id = current_user.id
    return jsonify(
        dict(
            approval_status=user.approval_status,
            approval_status_display=user.approval_status_display
        )
    )


@opc_wechat_bp.route('/wechat_template_list')
def wechat_template_list():
    """
    created by chenhj at 2017/7/25

    """
    page = request.args.get('page', 1, type=int)
    pagination = WechatTemplate.query.order_by(
        WechatTemplate.id
    ).paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False
    )
    wechat_templates = pagination.items
    return render_template(
        'wechat_template_list.html',
        wechat_templates=wechat_templates,
        pagination=pagination,
        page=page,
    )


@opc_wechat_bp.route('/wechat_template_add', methods=['GET', 'POST'])
def wechat_template_add():
    """
    created by chenhj at 2017/7/25

    """
    form = WechatTemplateForm()
    if form.validate_on_submit():
        wechat_template = WechatTemplate()
        form.populate_obj(wechat_template)
        db.session.add(wechat_template)
        flash('新增微信模板成功')
        return redirect(url_for('opc_wechat_bp.wechat_template_list'))
    return render_template('wechat_template_add.html', form=form)


@opc_wechat_bp.route('/wechat_template_edit/<int:template_id>', methods=['GET', 'POST'])
def wechat_template_edit(template_id: int):
    """
    created by chenhj at 2017/7/25

    """
    wechat_template = WechatTemplate.query.get_or_404(template_id)
    form = WechatTemplateForm(obj=wechat_template)

    if form.validate_on_submit():
        form.populate_obj(wechat_template)
        flash('修改成功')
        return redirect(url_for('opc_wechat_bp.wechat_template_list'))

    return render_template('wechat_template_edit.html', form=form)


@opc_wechat_bp.route('/wechat_send_log', methods=['GET', 'POST'])
def wechat_log_list():
    """
    微信发送记录
    """
    form = SearchWechatLogForm(formdata=request.form or request.args)

    log_query = WechatSendLog.query
    url_kwargs = {}
    if form.validate():
        _, url_kwargs = form.generate_kwargs()
        log_query = WechatSendLog.generate_list_query_condition(
            args=url_kwargs,
            query=log_query
        )
    page = request.args.get('page', 1, type=int)
    pagination = log_query.paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    logs = pagination.items

    return render_template(
        'wechat_log_list.html',
        form=form,
        logs=logs,
        pagination=pagination,
        url_kwargs=url_kwargs,
    )


@opc_wechat_bp.route('/wechat_tags')
def wechat_tags_list():
    """
    微信标签列表
    """
    page = request.args.get('page', 1, type=int)
    pagination = WechatTag.query.order_by(
        WechatTag.id
    ).paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False
    )
    wechat_tags = pagination.items
    return render_template(
        'wechat_tags_list.html',
        wechat_tags=wechat_tags,
        pagination=pagination,
        page=page,
    )


@opc_wechat_bp.route('/wechat_tags/pull')
def wechat_tags_pull():
    """
    created by chenhj at 2017/8/2
    从微信公众平台拉取微信用户标签
    """
    data = get_user_tags()
    tags = data['tags']
    for tag in tags:
        wechat_tag = WechatTag.get_by_args(tag_id=tag['id'])
        if not wechat_tag:
            wechat_tag = WechatTag.create(
                tag_id=tag['id']
            )
        wechat_tag.tag_name = tag['name']
        wechat_tag.user_count = tag['count']
    flash('拉取数据成功')
    return redirect(url_for('opc_wechat_bp.wechat_tags_list'))


@opc_wechat_bp.route('/wechat_menus')
def wechat_menus_list():
    """
    created by chenhj at 2017/8/3
    微信菜单列表
    """
    page = request.args.get('page', 1, type=int)
    pagination = WechatMenu.query.order_by(
        WechatMenu.id
    ).paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False
    )
    wechat_menus = pagination.items
    return render_template(
        'wechat_menus_list.html',
        wechat_menus=wechat_menus,
        pagination=pagination,
        page=page,
    )


@opc_wechat_bp.route('/wechat_menu_add', methods=['GET', 'POST'])
def wechat_menu_add():
    """
    created by chenhj at 2017/7/25
    新建菜单
    """
    form = WechatMenuForm()
    form.pid.choices = generate_menu_pid_choice()
    if form.validate_on_submit():
        menu = WechatMenu()
        form.populate_obj(menu)
        db.session.add(menu)
        flash('新增微信菜单成功')
        return redirect(url_for('opc_wechat_bp.wechat_menus_list'))
    return render_template('wechat_menu_add.html', form=form)


@opc_wechat_bp.route('/wechat_menu_edit/<int:menu_id>', methods=['GET', 'POST'])
def wechat_menu_edit(menu_id: int):
    """
    created by chenhj at 2017/7/25

    """
    menu = WechatMenu.query.get_or_404(menu_id)
    form = WechatMenuForm(obj=menu)
    form.pid.choices = generate_menu_pid_choice(menu_id)

    if form.validate_on_submit():
        form.populate_obj(menu)
        flash('修改成功')
        return redirect(url_for('opc_wechat_bp.wechat_menus_list'))

    return render_template('wechat_menu_edit.html', form=form)


@opc_wechat_bp.route('/wechat_menu_del/<int:menu_id>')
def wechat_menu_del(menu_id: int):
    """
    created by chenhj at 2017/7/25

    """
    menu = WechatMenu.query.get_or_404(menu_id)
    menu.deleted_at = 0 if menu.deleted_at else get_timestamp()
    flash('操作成功')
    return redirect(url_for('opc_wechat_bp.wechat_menus_list'))


@opc_wechat_bp.route('/wechat_menu/sync')
def wechat_menu_sync():
    """
    created by chenhj at 2017/8/3
    把本地的菜单同步到微信公众号菜单
    """
    print(sync_wechat_menu(WechatMenu.generate_json()))
    flash('同步到微信公众号成功')
    return redirect(url_for('opc_wechat_bp.wechat_menus_list'))


@opc_wechat_bp.route('/wechat/user_info/sync/<openid>')
def wechat_sync_user(openid):
    """
    created by chenhj at 2017/8/7
    同步微信用户信息到本地
    """
    wxuser = get_wxuser_info(openid)
    local_wxuser = WxUser.get_by_args(openid=openid)
    if not local_wxuser:
        local_wxuser = WxUser.create(openid=openid)
    if 'nickname' in wxuser:
        local_wxuser.subscribe = wxuser['subscribe']
        local_wxuser.nickname = wxuser['nickname'].encode('utf8')
        local_wxuser.sex = wxuser['sex']
        local_wxuser.language = wxuser['language']
        local_wxuser.city = wxuser['city']
        local_wxuser.province = wxuser['province']
        local_wxuser.country = wxuser['country']
        local_wxuser.headimgurl = wxuser['headimgurl']
        local_wxuser.subscribe_time = wxuser['subscribe_time']
        local_wxuser.remark = wxuser['remark']
        local_wxuser.groupid = wxuser['groupid']
        local_wxuser.tagid_list = wxuser['tagid_list']
    else:
        user = User.get_by_args(wx_openid=openid)
        if user:
            user.wx_openid = ''
    flash('同步成功')
    return redirect(url_for('op_bp.user_list', wx_openid=openid))
